import React from 'react';
import { View, Image, Linking } from 'react-native';
import SplashScreen from "react-native-splash-screen"
import { Lt, Color, Label, Dialog, Jpp, Jx, Images, Navigator, Button, Nav, Login, Storage, Touch, Cpush, cSys } from "./_utils";
import { Net, NET_RI, NET_NR, NET_ND, NET_NT } from "./_net"
import { PageGuide } from './PageGuide';
import { cTemp } from './_util';
import { ViewProtocol } from './ViewProtocol';
import { Overlay } from './_teaset';

// 进入首页(自动登录)
function toMainWithRole(roleId){
    cTemp.setRoleId(roleId);
    Cpush.checkedInterval();
    Navigator.reset("PageMain");
}

// 进入首页(非自动登录)
export function toMainWithToken(token, phone){
    if(token.userId && token.token){
        token = token.userId + "_" + token.token;
        Net._token = token;
        console.log("Net._token = ", token);
        Storage.save(Storage.SESSION, token);
        if(phone){
            Storage.save(Storage.ACCOUNT, phone);
        }
        Net.request("team/myRole", null, {NET_RI}).then(r=>{
            toMainWithRole(r.data);
        });
        return true;
    }
    console.log("token数据: ", Jx.stringify(token));
    return false;
}

export function toTaobao(r){
    if(r.data.url){
        Dialog.msg1(r.data.message, ()=>{
            Linking.openURL(r.data.url);
        }, "前往绑定", true);
        return true;
    }
    return false;
}

// 登录界面
export class PageAutoLogin extends React.PureComponent{
    constructor(props){
        super(props);

        this.state = {
            guide : false,
            wchat : false,
        }
        this.account = "";
        this.didMount = false;
        this.didLogin = false;
        this.switchUrl = 0;
        // 防止快速点击
        this.timeout = null;

        // 为安卓申请权限
        cSys.promiseCapturePermission(false);

        this.onWechatLogin = this.onWechatLogin.bind(this);
        this.onProtocol =  this.onProtocol.bind(this);
    }

    // 隐藏启动图
    doLogin(){
        this.didLogin = true;
        if(this.didMount){
            SplashScreen.hide();
        }
    }

    componentWillMount(){
        // 如果是从“退出登录/注销”进来的, 不会触发自动登录
        if(cTemp.isFromInfo()){
            Storage.promiseLoad(Storage.ACCOUNT).then(r=>{
                this.account = r;
            })
            if(cSys.isWechatInstalled()){
                this.setState({wchat:true});
            }
            return;
        }
        Dialog.retain(true);
        // 请求 原生信息/微信检测/QQ检测/本地存储/版本检测/审核检测/...
        Login.promiseLogin().then(obj=>{
            Dialog.release();
            console.warn(Jx.stringify(Jpp));
            if(!obj.applied){
                Navigator.reset("ApplyAutoLogin", { obj });
                return;
            }
            if(obj.url){
                Dialog.msg1("新的版本", ()=>{
                    Linking.openURL(obj.url);
                }, "前往下载", true);
                this.doLogin();
                return;
            }
            // 自动登录
            if(obj.tokenData != ""){
                toMainWithRole(obj.tokenData);
                return;
            }
            // 微信是否安装
            if(obj.isWeChatRegistered){
                cSys.checkWechatInstalled().then(wchat=>{
                    if (wchat){
                        this.setState({wchat:true});
                    }
                })
            }
            // 是否检测引导页
            if(obj.guide){
                this.setState({guide:true});
            }else{
                // 检测热更新
                Cpush.checkedInterval();
            }
            this.account = obj.account;
            this.doLogin();
        }).catch(err=>{
            Dialog.release();
        })
    }
    componentDidMount(){
        this.didMount = true;
        if(this.didLogin){
            SplashScreen.hide();
        }
    }
    componentWillUnmount(){
        if(this.timeout){
            clearTimeout(this.timeout);
            Dialog.release();
            this.timeout = null;
        }
    }

    static navigationOptions = {
        header : null,
    }

    // 微信登录
    onWechatLogin(){
        if(!cSys.isWechatInstalled(true)){
            return;
        }
        // 防止快速点击
        Dialog.retain();
        this.timeout = setTimeout(()=>{
            Dialog.release();
            this.timeout = null;
        }, 700);

        // 微信授权登录
        cSys.fetWchatRelease().then(wcData=>{
            Net.request("wxLogin", {wx:wcData.unionid}, {NET_NR}).then(r=>{
                Dialog.release();
                // 未绑定淘宝
                if(toTaobao(r)){
                    return;
                }
                // 登录成功
                toMainWithToken(r.data);
            }).catch(err=>{
                Dialog.release();
                // 绑定手机号
                this.onPhoneLogin(wcData);
            })
        }).catch(err=>{
            Dialog.release();
        });
    }

    // 手机登录
    onPhoneLogin(wcData){
        Navigator.push("PageLogin", {account : this.account, wcData});
    }

    // 用户协议
    onProtocol(){
        Overlay.hide(this.readRef);
        this.readRef = Overlay.show(<ViewProtocol
            onClose={()=>{Overlay.hide(this.readRef)}}
            onRead={()=>{
                Overlay.hide(this.readRef)
            }}
        />);
    }

    render(){
        const { guide, wchat } = this.state;
        return <View style = {{flex:1, justifyContent:"space-between", alignItems:"center"}}>
            <Nav.StatusBar/>
            <View style = {{height:"60%", justifyContent:"center", alignItems:"center"}}>
                <Touch
                    onPress={()=>++this.switchUrl} 
                    onLongPress={()=>{
                        if(this.switchUrl > 3){
                            Net.switchUrl();
                        }
                    }}
                >
                    <Image source = {Images.logo} />
                </Touch>
                <Label style = {{fontSize:Lt.c20, color:Color.c3, marginVertical:Lt.margin}}>{Jpp.gameName}</Label>
                <Label style = {{color:Color.c3}}>省钱更赚钱</Label>
            </View>
            <View style = {{height:"40%", justifyContent:"center", alignItems:"center"}}>
                <Button.FlexPure 
                    style = {{marginBottom:20}} 
                    title = { wchat ? "微信登录" : "手机登录" } 
                    onPress = {wchat ? this.onWechatLogin : this.onPhoneLogin.bind(this, null)}
                />
                {
                    (!wchat) ? null : 
                    <Button.Round style = {{
                        color:Color.c6,
                        fontSize:Lt.c16,
                    }}
                        title = {"手机快捷登录"}
                        onPress = {this.onPhoneLogin.bind(this, null)}
                    />
                }
                <View style={{marginTop:Lt.margin, flexDirection:"row", alignItems:"center", alignSelf:"center"}}>
                    <Touch style={{padding:Lt.pad}} onPress={this.onProtocol}>
                        <View style={{flexDirection:"row", alignItems:'center'}}>
                            <Image source={Images.yuandu_gou}/>
                            <Label style = {{color:Color.c9}}> 我已阅读用户协议</Label>
                        </View>
                    </Touch>
                </View>
            </View>
            <PageGuide isHiden={!guide} onClick={Login.saveGuide.bind(Login, true)}/>
        </View>;
    }
}